<template>
  <div class="info">
    <van-form @submit="onSubmit" :model-value="detailData" class="table-form" :onload="loading">
      <van-field name="avatar" label="头像">
        <template #input>
          <van-uploader
            multiple
            :max-count="1"
            v-model="avatarList"
            :max-size="4000 * 1024"
            @oversize="onOversize"
            :after-read="afterReadCover"
          />
        </template>
      </van-field>
      <van-field
        v-model="detailData.nickname"
        name="nickname"
        label="昵称"
        placeholder="昵称"
        :rules="[{ required: true, message: '请填写昵称' }]"
      />
      <van-field
        v-model="detailData.email"
        name="email"
        label="邮箱"
        placeholder="邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]"
      />
      <van-field
        v-model="genderMap[detailData.sex]"
        is-link
        readonly
        name="sex"
        label="性别"
        placeholder="点击选择性别"
        @click="showPicker = true"
      />
      <van-field name="age" label="年龄">
        <template #input>
          <van-stepper v-model="detailData.age" />
        </template>
      </van-field>
      <van-field
        v-model="detailData.address"
        is-link
        readonly
        name="area"
        label="地区"
        placeholder="点击选择省市区"
        @click="showArea = true"
      />
      <van-field
        class="introduce-cell"
        v-model="detailData.introduce"
        name="introduce"
        label="介绍"
        placeholder="请填写介绍"
        rows="3"
        autosize
        type="textarea"
      />
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>
    <van-popup v-model:show="showPicker" position="bottom">
      <van-picker v-model="sexValues" :columns="genderList" @confirm="onSexConfirm" @cancel="showPicker = false" />
    </van-popup>
    <van-popup v-model:show="showArea" position="bottom">
      <van-area :area-list="areaList" @confirm="onAreaConfirm" @cancel="showArea = false" />
    </van-popup>
  </div>
</template>

<script setup lang="ts">
  import { getFileHttpUrl } from '@/utils/urlUtils';
  import { message } from 'ant-design-vue';
  import { showToast } from 'vant';
  import { uploadFile } from '@/api/comment';
  import useRequestDetail from '@/hooks/useRequestDetail';
  import { updatePersonal, userApi } from '@/api/user';
  import { genderList, genderMap } from '@/enums/userUpdateEnum';
  import { areaList } from '@vant/area-data';

  const router = useRouter();
  const avatarList = ref<{ url: string }[]>([]);
  const showPicker = ref(false);
  const showArea = ref(false);
  const sexValues = ref([0]);

  const { detailData, loading, getDetail } = useRequestDetail({
    apiKey: userApi.userDetail,
  });

  const getData = async () => {
    getDetail().then(() => {
      if (detailData.value) {
        const image = { url: getFileHttpUrl(detailData.value.avatar) };
        avatarList.value.push(image);
        // 性别
        sexValues.value = [];
        sexValues.value.push(detailData.value.sex);
      }
    });
  };

  /**
   * 性别
   * @param selectedOptions
   */
  const onSexConfirm = ({ selectedOptions }) => {
    detailData.value.sex = selectedOptions[0]?.value;
    showPicker.value = false;
  };

  /**
   * 地区
   * @param selectedOptions
   */
  const onAreaConfirm = ({ selectedOptions }) => {
    showArea.value = false;
    detailData.value.address = selectedOptions.map((item) => item.text).join('');
  };

  const onSubmit = async () => {
    const res = await updatePersonal({ ...detailData.value });
    if (res) {
      message.success(res?.msg);
      router.go(-1);
    }
  };

  /**
   * 图片上传
   */
  const onOversize = () => {
    showToast('图片大小不能超过 4Mb');
  };
  const afterReadCover = async (file: any) => {
    // 此时可以自行将文件上传至服务器
    const coverFormData = new FormData();
    coverFormData.append('file', file.file);
    const res = await uploadFile(coverFormData);
    if (res) {
      if (res.code === 0) {
        const url = res.data.url;
        // 赋值
        detailData.value.avatar = url;
        avatarList.value = [];
        avatarList.value.push({ url: getFileHttpUrl(url) });
        return res.data.url;
      }
    }
  };

  onMounted(async () => {
    await getData();
  });
</script>

<style lang="scss" scoped>
  .nut-swiper-item {
    line-height: 500px;
    img {
      width: 100%;
      height: 100%;
    }
  }

  .info {
    padding: 20px;
    .table-form {
      .introduce-cell {
        margin-top: 30px;
      }
    }
  }
  .rustic-list {
    background: #e2e8ef;
    .intro-header {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 20px;
      font-size: 16px;
      width: 100%;
    }
  }
</style>
